import { _decorator, Component, Node, Label } from 'cc';
import {GameType} from "db://assets/script/game/constants/common";
import {smc} from "db://assets/script/game/common/singletonModuleComp";
import {api} from "db://assets/script/game/player/api";
import {pb} from "db://assets/script/network/ws/proto";
const { ccclass, property } = _decorator;

@ccclass('CategoryCellView')
export class CategoryCellView extends Component {
    @property({
        type: Label,
        tooltip: '场次名'
    })
    categoryName: Label;

    @property({
        type: Label,
        tooltip: '底分倍率'
    })
    diFenRate: Label;

    @property({
        type: Label,
        tooltip: '金豆门槛'
    })
    rubyNumber: Label;

    @property({
        type: Label,
        tooltip: '在线人数'
    })
    onlineNumber: Label;

    @property({
        type: Node,
        tooltip: '事件点击捕获'
    })
    eventUI: Node;

    gameType: string
    conf: pb.ICategoryItem
    start() {
        this.activeClick()
    }

    setConf(conf: pb.ICategoryItem, gameType: string) {
        this.conf = conf
        this.gameType = gameType
    }

    updateView() {
        // 更新场次名
        this.categoryName.string = this.conf.itemName
        // 更新在线人数
        this.onlineNumber.string = this.conf.onlineCount.toString()
        // 底分
        this.diFenRate.string = this.conf.diFenRate.toString()
        // 金豆限制
        this._updateRubyNumber()
    }

    _updateRubyNumber() {
        let s = this.conf.minRuby.toString()
        if (this.conf.maxRuby > this.conf.minRuby) {
            // 有上限
            s += "~" + this.conf.maxRuby.toString()
        } else {
            // 没有上限
            s = ">=" + this.conf.minRuby.toString()
        }
        this.rubyNumber.string = s
    }

    // 创建房间
    async clickCreateDesk() {
        this.inactiveClick()
        const mjOpt: pb.IMjDeskOpt = {}
        let onSuccess: Function
        switch (this.gameType) {
            case GameType.mj:
                // 检查是否能建房
                mjOpt.playerCount = 4
                mjOpt.totalRound = 1
                mjOpt.isRuby = true
                mjOpt.isPrivate = false
                mjOpt.isClub = false
                onSuccess = (resp: pb.IDeskCreateDeskInfo) => {
                    smc.gameMj.addInitComp(resp.deskInfo, [resp.playerInfo], this.conf, false, [], null, null)
                    // 重新允许点击
                    this.activeClick()
                }
                break
            default:
                console.error("no such game type", this.gameType)
        }
        api.deskCreateDesk({
            gameType: this.gameType,
            mjOpt,
        }, onSuccess, this.activeClick.bind(this), true)
    }

    activeClick() {
        this.eventUI.on(Node.EventType.TOUCH_START, this.clickCreateDesk.bind(this))
    }

    inactiveClick() {
        this.eventUI.off(Node.EventType.TOUCH_START)
    }
}


